package com.oceansoft.mobile.biz.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.oceansoft.mobile.biz.api.entity.Member;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.util.HttpClientUtil;
import com.oceansoft.mobile.common.util.Result;
import com.oceansoft.mobile.weixin.util.RequestUtils;
import com.oceansoft.mobile.weixin.util.WeixinUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;

/**
 * Created by zhangxl on 2017/2/27.
 */
@Controller
@RequestMapping("api/chemical")
public class ApiChemicalController {

    /**
     * 获取事项对应的部门
     * http://172.16.1.101:8080/api/police/BMByCasename?casename=
     *
     * @return result
     */
    @ResponseBody
    @RequestMapping(value = "getDept")
    public Result getDept(HttpServletRequest request) throws IllegalArgumentException, IOException {


        String name = URLDecoder.decode(request.getParameter("casename"), "UTF-8");
        String url = Constant.host5+"api/police/BMByCasename?casename="+name;
//        System.out.println(url);
        JSONObject json = JSONObject.parseObject(HttpClientUtil.doGet(url));

        Result result = new Result(json);
//        System.out.println(result);
        return result;
    }

    /**
     * 根据分局获取事项对应的部门
     * http://172.16.1.101:8080/api/police/PoliceByCasename
     * casename  hierarchy
     *
     * @return result
     */
    @ResponseBody
    @RequestMapping(value = "getDeptByPoliceStation")
    public Result getDeptByPoliceStation(HttpServletRequest request) throws IllegalArgumentException, IOException {

        String orgid = request.getParameter("orgid");
        Map<String, String> params = new HashMap<>() ;
        String name = URLDecoder.decode(request.getParameter("casename"), "UTF-8");
        params.put("casename",name);
        params.put("hierarchy",orgid);
        String url = Constant.host5+"api/police/PoliceByCasename";
//        System.out.println(url);
        JSONObject json = JSONObject.parseObject(HttpClientUtil.doPost(url,params,"UTF-8"));

        Result result = new Result(json);
//        System.out.println(result);
        return result;
    }

    /**
     * 获取事项对应的分局
     * http://172.16.1.101:8080/api/police/FJByCasename?casename=
     *
     * @return result
     */
    @ResponseBody
    @RequestMapping(value = "getPoliceStation")
    public Result getPoliceStation(HttpServletRequest request) throws IllegalArgumentException, IOException {

        String name = URLDecoder.decode(request.getParameter("casename"), "UTF-8");
        String url = Constant.host5+"api/police/FJByCasename?casename="+name;
        System.out.println(url);
        JSONObject json = JSONObject.parseObject(HttpClientUtil.doGet(url));

        Result result = new Result(json);
//        System.out.println(result);
        return result;
    }

    /**
     * 获取事项对应的事项详情
     * http://172.16.1.101:8080/api/getcase/GetCaseInfo2?refID= &orgId=&casename=
     *
     * @return result
     */
    @ResponseBody
    @RequestMapping(value = "detail")
    public Result getdetail(HttpServletRequest request) throws IllegalArgumentException, IOException ,JSONException {

        String refguid = (String) request.getSession().getAttribute("refguid");
        String orgid = (String) request.getSession().getAttribute("orgid");
        String casename = (String) request.getSession().getAttribute("casename");
        String url = Constant.host5+"api/getcase/GetCaseInfo2?refID="+refguid+"&orgId="+orgid+"&casename="+casename;//

        JSONObject json = JSONObject.parseObject(HttpClientUtil.doGet(url));

        String url1 =Constant.host5+"api/getcase/GetCaseBasisList?caseRefId="+refguid;//获取事项依据列表

        JSONObject json1 = JSONObject.parseObject(HttpClientUtil.doGet(url1));
        System.out.println(json1.get("data").toString());

        JSONArray j=JSONObject.parseArray(json1.get("data").toString());
        String s="";
        if(j.size()!=0) {
            for (int i = 0; i <j.size(); i++) {
                try {
                    s += j.getJSONObject(i).get("BASISCONTENT").toString()+"<br>";
                } catch (NullPointerException e) {
                   /* e.printStackTrace();*/
                }
            }
        }

        json.put("xkyj",s);

        String url2 =Constant.host5+"api/getcase/GetCaseMaterial?refID="+refguid;//事项材料列表
        System.out.print(url2);
        JSONObject json2 = JSONObject.parseObject(HttpClientUtil.doGet(url2));


        JSONArray jj=JSONObject.parseArray(json2.get("data").toString());
        String sqcl="";
        if(jj.size()>0){
            for(int i=0;i<jj.size();i++){
                String str = (i+1)+"、"+jj.getJSONObject(i).get("MATERIAL").toString()+" <br/> ";
                sqcl += str;
            }
        }

        json.put("sqcl",sqcl);


        Result result = new Result(json);
//        System.out.println(result);
        return result;
    }


    /**
     * 从事项和部门选择页跳转到须知页面
     */
    @ResponseBody
    @RequestMapping(value = "gotopage/{pageName}")
    public void gotoMattersPage(@PathVariable("pageName") String pageName, HttpServletRequest request, Model model) {

//        request.getSession().setAttribute("yzdhxp",param);
//        Map<String, String> param1 = ( Map<String, String>)request.getSession().getAttribute("yzdhxp");

        request.getSession().setAttribute("refguid", request.getParameter("refguid"));
        request.getSession().setAttribute("refid", request.getParameter("refid"));
        request.getSession().setAttribute("orgid", request.getParameter("orgid"));
        try {
            request.getSession().setAttribute("casename", URLDecoder.decode(request.getParameter("orgname"), "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从菜单页面跳转到选择事项和部门页面
     */
    @RequestMapping("getPage/{pageName}")
    public String getPage(@PathVariable("pageName") String pageName, HttpServletRequest request, HttpSession session,Model model) {



        Member member = (Member) session.getAttribute(Constant.SESSION_USER);
        model.addAttribute("data", member);

        String source = (String) request.getSession().getAttribute("source");
        if (!com.oceansoft.mobile.common.util.StringUtils.isEmpty(source)) {
            model.addAttribute("source", source);
        }
//        System.out.println("=====weixin/chemical/" + pageName);
        return "weixin/chemical/" + pageName;
    }

    /**
     * 申报
     */
    @ResponseBody
    @RequestMapping(value="applyYzdhxpMsg",method= RequestMethod.POST)
    public Result applyYzdhxpMsg(HttpServletRequest request,@RequestParam("declareCaseGuid") String declareCaseGuid){
        Map<String, String> param = (Map<String, String>)request.getSession().getAttribute("yzdhxp");
        Result result = RequestUtils.submitShenbao(RequestUtils.map2Json(param),request, "", "yzdhxp_fj", true);
        request.getSession().removeAttribute("yzdhxp");
        return result;
    }

    /**
     * 申请
     */
    @ResponseBody
    @RequestMapping(value = "yzdhxp", method = RequestMethod.POST)
    public Result applyYzdHxp(HttpServletRequest request) {
        Map<String, String> param = new HashMap<String, String>();
        param = RequestUtils.buildParamsByNamesFromRequest(request);
        param.put("refid",(String) request.getSession().getAttribute("refguid"));
        param.put("orgId",(String) request.getSession().getAttribute("orgid"));
        param.put("caseName",(String) request.getSession().getAttribute("casename"));
        param.put("declareCaseGuid",(String) request.getSession().getAttribute("refid"));
        request.getSession().setAttribute("yzdhxp", param);
        return new Result();
    }

    /**
     * 图片上传
     * @param type
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value="uploadMsgYZDHXP",method=RequestMethod.POST)
    public Result uploadMsgYZDHXP(@RequestParam("type")String type,MultipartHttpServletRequest request){
        String caseMatGuid = type;
        //type字段用于识别前台传过来的不同图片
        //type_1
        //Result result = uploadFJ(type, request, "pzctrl",type);
        Result result = RequestUtils.saveFj(request, "pzctrl", caseMatGuid, false);
        Map<String ,Result> m = (Map<String ,Result>)request.getSession().getAttribute("yzdhxp_fj");
        request.getSession().removeAttribute("yzdhxp_fj");
        if(null==m)
        {
            m = new HashMap<String ,Result>();
        }
        m.put("yzdhxp_fj"+type, result);
        request.getSession().setAttribute("yzdhxp_fj", m);
        //System.out.println("门牌号码的附件包含"+m.toString());
        return result;
    }


    /**
     * 从申报信息页面跳转到上传信息页面
     * http://172.16.1.101:8080/api/SXInfo/GetSXInfoBy?caseName= &orgGuid=
     */
    @RequestMapping(value = "yzd23hxpgmba", method = RequestMethod.GET)
    public String applyYzdhxp(HttpServletRequest request, Model model)throws IllegalArgumentException, IOException {

        String orgid = (String) request.getSession().getAttribute("orgid");
        String casename = (String) request.getSession().getAttribute("casename");

        Map<String, String> param = new HashMap<String, String>();
        param = (Map<String, String>)request.getSession().getAttribute("yzdhxp");

        String url = Constant.host5+"api/SXInfo/GetSXInfoBy?caseName="+casename+"&orgGuid="+orgid;
//        System.out.println(url);
        Result rr = JSONObject.parseObject(HttpClientUtil.doGet(url), Result.class);
        model.addAttribute("cl", rr);
        return "weixin/chemical/yzdhxp";
    }

    /**
     * 新增一个需要登录的跳转控制
     *
     * @return
     */
    @RequestMapping(value = "gotopageWithUser/{pageName}")
    public String gotoMattersPageWithUser(@PathVariable("pageName") String pageName, HttpServletRequest request, Model model) throws IllegalArgumentException, IOException {
        boolean b = WeixinUtil.checkIsLoginUser(request);
        String source = (String) request.getSession().getAttribute("source");
        if (!StringUtils.isEmpty(source)) {
            model.addAttribute("source", source);
        }
//        b=true;
        if (!b) {
            model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
            model.addAttribute("gotoPage", "/api/chemical/gotopageWithUser/" + pageName);
            return "weixin/login/login";
        } else {
            Member member = (Member) request.getSession().getAttribute(Constant.SESSION_USER);
            model.addAttribute("data", member);
            return "weixin/chemical/" + pageName;
        }
    }

    /**
     * 提示jsp页面跳转jsp信息页面
     *
     * @param state
     * @param request
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "gotoPageByUserAll/{state}", method = RequestMethod.GET)
    public String gotoPages(@PathVariable("state") String state,
                            HttpServletRequest request, Model model, HttpSession session) {
        model.addAttribute("openId", (String) request.getSession().getAttribute("openId"));
        model.addAttribute("state", state);
        String url = Constant.stateMap.get(state);
        if (StringUtils.isEmpty(url)) {
            url = Constant.stateMap.get("0");
        }
        model.addAttribute("url", url);
        Member member = (Member) session.getAttribute(Constant.SESSION_USER);
        model.addAttribute("data", member);
        String source = (String) request.getSession().getAttribute("source");
        if (!StringUtils.isEmpty(source)) {
            //model.addAttribute("source", source);
            if (url.indexOf("?") >= 0) {
                url += "&source=" + source;
            } else {
                url += "?source=" + source;
            }

        }

        return "redirect:" + url;

    }
}
